<template>
  <div class="w-full h-[100vh]">
    <div
      class="bg-[#4f6bdf] h-[60px] text-white flex items-center justify-center"
    >
      {{ examName }}
    </div>
    <n-layout has-sider class="h-[80vh]">
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="10"
        :width="200"
        show-trigger
      >
        <n-menu
          :options="leftChapter"
          style="width: 200px"
          @update:value="handleLeftChange"
        />
      </n-layout-sider>
      <n-layout>
        <n-data-table
          :loading="loading"
          :columns="columns"
          :data="tableData"
          :cascade="false"
          allow-checking-not-loaded
          @load="onLoad"
        />
      </n-layout>
    </n-layout>
  </div>

  <ActiveCodeInput
    :exam-id="curExamId"
    :show-modal="showModal"
    @close="showModal = false"
  ></ActiveCodeInput>
</template>

<script setup lang="ts">
import type { DataTableColumns } from 'naive-ui'
import { getChapterByPage } from '@/api/chapter'
import type { ChapterRes } from '@/types/chapter'
import { getPaperByPage } from '@/api/paper'
import router from '@/router'
import useUserStore from '@/stores/modules/user'
import { getUserActiveExamByPage } from '@/api/userActiveExam'
import { removeItem } from '@/utils/storage'
import { Users } from '@vicons/fa'
import { getErrorPaperByPage } from '@/api/errorQuestion'
import { uniqueArrayByKey } from '@/utils'
import { getPaperFavByPage } from '@/api/questionFav'

const route = useRoute()
const userStore = useUserStore()
const leftChapter = ref<ChapterRes[]>([])
const curExamId = ref('')
const showModal = ref(false)
const examName = ref('')
const curChapterId = ref('')

const loadChapters = (pid = '-1') => {
  return new Promise((resolve) => {
    getChapterByPage({
      page: 1,
      pageSize: 9999,
      pid,
      examId: route.query.examId as string
    })
      .then((res) => {
        if (res.data.items.length) {
          examName.value = res.data.items[0].Exam.name
        }
        resolve(res.data.items)
      })
      .catch(() => {
        resolve([])
      })
  })
}

onMounted(() => {
  curExamId.value = route.query.examId as string
  loadChapters().then((res: any) => {
    leftChapter.value = res.map((item: any) => {
      return {
        ...item,
        key: item.id,
        label: item.name
      }
    })
    console.log(leftChapter.value, 'left')

    // push两个我的错题和我的收藏

    const pushArr = [
      {
        id: '-3',
        name: '我的错题',
        label: '我的错题',
        key: '-3',
        pid: '-1',
        examId: '-1',
        ParentChapter: null,
        Exam: null,
        createTime: '-1'
      },
      {
        id: '-4',
        name: '我的收藏',
        label: '我的收藏',
        key: '-4',
        pid: '-1',
        examId: '-1',
        ParentChapter: null,
        Exam: null,
        createTime: '-1'
      }
    ]

    leftChapter.value.push(...pushArr)
  })
})

const tableData = ref<any>([])

const loading = ref(false)
const handleLeftChange = (key: string, menuItem: any) => {
  loading.value = true
  curChapterId.value = key
  // 选中左侧，右侧table数据发生变化
  if (!menuItem.childLen) {
    // 根据key不同调用不同的接口
    if (key === '-3') {
      // 加载我的错题
      getErrorPaperByPage({
        page: 1,
        pageSize: 9999,
        examId: route.query.examId as string
      })
        .then((res: any) => {
          const papers = res.data.items.map((item: any) => {
            item.Paper.questionCnt = item.questionCnt
            return item.Paper
          })
          // 对象数组去重
          tableData.value = uniqueArrayByKey(papers, 'id')
        })
        .finally(() => {
          loading.value = false
        })
    } else if (key === '-4') {
      // 加载我的收藏
      getPaperFavByPage({
        page: 1,
        pageSize: 9999,
        examId: route.query.examId as string
      })
        .then((res: any) => {
          const papers = res.data.items.map((item: any) => {
            item.Paper.questionCnt = item.questionCnt
            return item.Paper
          })
          // 对象数组去重
          tableData.value = uniqueArrayByKey(papers, 'id')
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      // 加载paper
      getPaperByPage({
        page: 1,
        pageSize: 9999,
        chapterId: key
      })
        .then((res: any) => {
          tableData.value = res.data.items.map((item: any) => {
            return {
              ...item,
              key: item.id,
              isLeaf: true
            }
          })
        })
        .finally(() => {
          loading.value = false
        })
    }
  } else {
    loadChapters(key).then((res: any) => {
      tableData.value = res.map((item: any) => {
        return {
          ...item,
          key: item.id,
          isLeaf: false
        }
      })
    })
  }
}

const columns: DataTableColumns = [
  { key: 'name', title: '名称' },
  { key: 'questionCnt', title: '数量' },
  { key: 'time', title: '考试时长(分钟)' },
  {
    key: 'action',
    title: '操作',
    render: (row) => {
      if (row.chapterId) {
        return h('div', [
          h(
            NButton,
            {
              text: true,
              type: 'success',
              size: 'small',
              onClick: () => handleToAnswer(row)
            },
            { default: () => '开始做题' }
          ),
          // 需要用户存在作答记录
          renderHasHistory(row) &&
            h(
              NButton,
              {
                text: true,
                type: 'warning',
                size: 'small',
                class: 'ml-2',
                onClick: () => handleToViewPort(row)
              },
              { default: () => '查看解析' }
            )
        ])
      } else {
        return ''
      }
    }
  }
]

const onLoad = (row: Record<string, unknown>) => {
  return new Promise<void>((resolve) => {
    // 根据row的情况渲染
    if (row.childLen === 0) {
      // 加载paper
      getPaperByPage({
        page: 1,
        pageSize: 9999,
        chapterId: row.id as string
      }).then((res: any) => {
        row.children = res.data.items.map((item: any) => {
          return {
            ...item,
            key: item.id,
            isLeaf: true
          }
        })
        resolve()
      })
    } else {
      // 加载章节
      loadChapters(row.id as string).then((res: any) => {
        row.childLen = res.map((item: any) => {
          return {
            ...item,
            key: item.id,
            isLeaf: false
          }
        })
        resolve()
      })
    }
  })
}

const handleToAnswer = async (row: any) => {
  if (!userStore.token) {
    router.replace({
      name: 'login'
    })
    return
  }

  // 需要用户激活了该科考试
  if (!userStore.userInfo) {
    await userStore.getUserInfo()
  }

  const res = await getUserActiveExamByPage({
    page: 1,
    pageSize: 10,
    examId: route.query.examId as string,
    userId: userStore.userInfo?.id
  })
  if (res.data.items.length > 0) {
    removeItem(row.id + 'time')
    removeItem(row.id + 'answer')
    removeItem(row.id + 'currentIndex')
    // 获取type类型
    let type = 1
    if (curChapterId.value === '-3') {
      type = 2
    } else if (curChapterId.value === '-4') {
      type = 3
    }
    router.push({
      name: 'paperDetail',
      query: {
        paperId: row.id,
        examId: route.query.examId,
        type
      }
    })
  } else {
    // 说明没有激活，提示激活码
    showModal.value = true
  }
}

const renderHasHistory = (item: any) => {
  // return item.ExamHistories
  if (!userStore.userInfo?.id) {
    return false
  }
  // if()
  const has = item.ExamHistories.filter(
    (v: any) => v.userId === userStore.userInfo?.id
  )
  // console.log(has, 'has')

  if (curChapterId.value === '-3') {
    return has.length > 0 && has.some((v: any) => v.type === 2)
  }
  if (curChapterId.value === '-4') {
    return has.length > 0 && has.some((v: any) => v.type === 3)
  }
  return has.length > 0 && has.some((v: any) => v.type === 1)
}

// 查看解析
const handleToViewPort = async (row: any) => {
  if (!userStore.token) {
    router.replace({
      name: 'login'
    })
    return
  }

  // 需要用户激活了该科考试
  if (!userStore.userInfo) {
    await userStore.getUserInfo()
  }
  const res = await getUserActiveExamByPage({
    page: 1,
    pageSize: 10,
    examId: route.query.examId as string,
    userId: userStore.userInfo?.id
  })
  if (res.data.items.length > 0) {
    removeItem(row.id + 'time')
    removeItem(row.id + 'answer')
    // 获取type类型
    let type = 1
    if (curChapterId.value === '-3') {
      type = 2
    } else if (curChapterId.value === '-4') {
      type = 3
    }

    router.push({
      name: 'paperResult',
      query: {
        paperId: row.id,
        examId: route.query.examId,
        show: 1,
        type
      }
    })
  } else {
    // 说明没有激活，提示激活码
    showModal.value = true
  }
}
</script>

<style lang="scss" scoped></style>
